package com.dindang.maintenance.mvp.ui.adapter.custom;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dindang.maintenance.R;

import java.util.List;

/**图片 数据适配器*/
public class MaintainImageViewAdapter extends RecyclerView.Adapter<MaintainImageViewAdapter.ViewHolder> {

    List<String> list;//图片集合
    int width = 0;//图片宽度
    private OnClickListener listener;
    public MaintainImageViewAdapter(List<String> list) {
        this.list = list;
    }

    public void setListener(OnClickListener listener){
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.maintenance_item_image, parent, false);
        MaintainImageViewAdapter.ViewHolder viewHolder = new MaintainImageViewAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String imagePath = list.get(position);
        ViewGroup.LayoutParams layoutParams = holder.ll_image.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = width;

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.maintenance_ic_load_image)
                .error(R.mipmap.maintenance_ic_load_image);

        Glide.with(holder.iv_image.getContext())
                .asBitmap()
                .apply(options)
                .load(imagePath)
                .into(holder.iv_image);

        holder.iv_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onClick(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void setImageWidth(int width) {
        this.width = width / 4;
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout ll_image;
        ImageView iv_image;
        ViewHolder(View itemView) {
            super(itemView);
            ll_image = itemView.findViewById(R.id.maintenance_ll_image);
            iv_image = itemView.findViewById(R.id.maintenance_iv_image);
        }
    }

    public interface OnClickListener{
        void onClick(int position);
    }

}